﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml.Linq;
using MM.DBUtility;

namespace MobileManager.InfoManage
{
    public partial class AreaManage : System.Web.UI.Page
    {
        private MM.Model.T_Users userModel;
        private bool bolFlag = true;
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (Session["CurUser"] == null)
                {
                    Response.Redirect("Login.aspx");
                    return;
                }
                else
                {
                    userModel = (MM.Model.T_Users)Session["CurUser"];
                    if (userModel.RoleID.Equals("3"))
                        return;
                }
                if (!IsPostBack)
                {
                    BindDdlODEP(ref ddlODEP);
                    ddlODEP.Items.Insert(0, new ListItem("全部", "-1"));

                    GVDataBindAll();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        private void BindDdlODEP(ref DropDownList ddl)
        {
            ddl.DataSource = DbHelperSql.Query("SELECT ONO,ONO+'-'+ OName as Name FROM T_ODEP WITH(NOLOCK) ").Tables[0];
            ddl.DataValueField = "ONO";
            ddl.DataTextField = "Name";
            ddl.DataBind();
        }
        protected void btnADD_Click(object sender, EventArgs e)
        {
            try
            {
                if ("-1".Equals(ddlODEP.SelectedValue))
                {
                    MM.Common.Common.PageStartAlert(this.Page, "必须选择运营商！");
                    return;
                }
                string strAreaID = txtAreaID.Text.Trim();
                if (string.IsNullOrEmpty(strAreaID))
                {
                    MM.Common.Common.PageStartAlert(this.Page, "区域号不能为空！");
                    return;
                }
                if (BLSqlData.ExistAreaNO(strAreaID, ddlODEP.SelectedValue))
                {
                    MM.Common.Common.PageStartAlert(this.Page, "区域号+运营商已经存在，请更换！");
                    return;
                }
                string strCityName = txtCityName.Text.Trim();
                if (string.IsNullOrEmpty(strCityName))
                {
                    MM.Common.Common.PageStartAlert(this.Page, "城市名不能为空！");
                    return;
                }
                string strProvinceID = MM.DBUtility.BLSqlData.GetProvinceIDbyQuickName(txtProvince.TextValue);
                if (string.IsNullOrEmpty(strProvinceID))
                {
                    MM.Common.Common.PageStartAlert(this.Page, "必须选择省份，或省份选择错误！");
                    return;
                }

                string strSQL = string.Format("INSERT INTO T_Area(AreaNO,CityName,ProvinceID,ONO) VALUES('{0}',N'{1}',{2},'{3}')", strAreaID, strCityName, strProvinceID, ddlODEP.SelectedValue);
                MM.DBUtility.DbHelperSql.ExecuteSql(strSQL);
                MM.DBUtility.BLSqlData.InsertLogs(userModel.UserID, string.Format("添加了区域信息：区域号={0}。", strAreaID), "区域管理");
                MM.Common.Common.PageStartAlert(this.Page, "添加成功！");
                GVDataBindAll();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        protected void btnQuery_Click(object sender, EventArgs e)
        {
            try
            {
                AspNetPager1.CurrentPageIndex = 1;
                GVDataBind();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        protected void btnQueryAll_Click(object sender, EventArgs e)
        {
            try
            {
                AspNetPager1.CurrentPageIndex = 1;
                GVDataBindAll();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        #region GV info
        private void GVDataBind()
        {
            bolFlag = true;

            string strSQL = "SELECT a.ID,a.AreaNO,a.CityName,a.ProvinceID,b.ProvinceName,a.ONO,c.OName FROM T_Area a,T_Province b,T_ODEP c WITH(NOLOCK) WHERE a.ProvinceID=b.ProvinceID AND a.ONO=c.ONO ";

            string strWhere = string.Empty, strOrder = string.Empty;
            if (!string.IsNullOrEmpty(txtAreaID.Text.Trim()))
                strWhere += string.Format(" AND a.AreaNO LIKE '%{0}%'", txtAreaID.Text.Trim());
            if (!string.IsNullOrEmpty(txtCityName.Text.Trim()))
                strWhere += string.Format(" AND a.CityName LIKE N'%{0}%'", txtCityName.Text.Trim());

            string strProvinceID = MM.DBUtility.BLSqlData.GetProvinceIDbyQuickName(txtProvince.TextValue);
            if (!string.IsNullOrEmpty(strProvinceID))
                strWhere += string.Format(" AND a.ProvinceID={0}", strProvinceID);
            if (!"-1".Equals(ddlODEP.SelectedValue))
                strWhere += string.Format(" AND a.ONO='{0}'", ddlODEP.SelectedValue);

            if ("PinYinCode".Equals(ddlOrder.SelectedValue))
                strOrder = string.Format(" ORDER BY b.PinYinCode {0}", ddlAD.SelectedValue);
            else strOrder = string.Format(" ORDER BY a.{0} {1}", ddlOrder.SelectedValue, ddlAD.SelectedValue);

            AspNetPager1.RecordCount = DbHelperSql.GetCount("SELECT COUNT(1) FROM T_Area a WHERE 1=1 " + strWhere);

            if (AspNetPager1.CurrentPageIndex == 1)
                strSQL = strSQL.Replace("SELECT", string.Format("SELECT TOP {0}", AspNetPager1.PageSize)) + strWhere;
            else
                strSQL = strSQL.Replace("SELECT", string.Format("SELECT TOP {0}", AspNetPager1.PageSize)) + strWhere + string.Format("AND a.ID NOT IN (SELECT TOP {0} a.ID FROM T_Area a,T_Province b,T_ODEP c WHERE a.ProvinceID=b.ProvinceID AND a.ONO=c.ONO {1} {2})", (AspNetPager1.CurrentPageIndex - 1) * AspNetPager1.PageSize, strWhere, strOrder) + strOrder;

            DataSet ds = DbHelperSql.Query(strSQL);
            GVinfo.DataSource = ds;
            GVinfo.DataBind();
            ViewState["DataTemp"] = ds;
            lbCount.Text = "记录数：" + AspNetPager1.RecordCount;
        }
        private void GVDataBindAll()
        {
            bolFlag = false;
            string strSQL = "SELECT a.ID,a.AreaNO,a.CityName,a.ProvinceID,b.ProvinceName,a.ONO,c.OName FROM T_Area a,T_Province b,T_ODEP c WITH(NOLOCK) WHERE a.ProvinceID=b.ProvinceID AND a.ONO=c.ONO";

            string strOrder = string.Empty;
            if ("PinYinCode".Equals(ddlOrder.SelectedValue))
                strOrder += string.Format(" ORDER BY b.PinYinCode {0}", ddlAD.SelectedValue);
            else strOrder += string.Format(" ORDER BY a.{0} {1}", ddlOrder.SelectedValue, ddlAD.SelectedValue);

            AspNetPager1.RecordCount = DbHelperSql.GetCount("SELECT COUNT(1) FROM T_Area a");

            if (AspNetPager1.CurrentPageIndex == 1)
                strSQL = strSQL.Replace("SELECT", string.Format("SELECT TOP {0}", AspNetPager1.PageSize));
            else
                strSQL = strSQL.Replace("SELECT", string.Format("SELECT TOP {0}", AspNetPager1.PageSize)) + string.Format("AND a.ID NOT IN (SELECT TOP {0} a.ID FROM T_Area a,T_Province b,T_ODEP c WHERE a.ProvinceID=b.ProvinceID AND a.ONO=c.ONO {1} )", (AspNetPager1.CurrentPageIndex - 1) * AspNetPager1.PageSize, strOrder) + strOrder;

            DataSet ds = DbHelperSql.Query(strSQL);
            GVinfo.DataSource = ds;
            GVinfo.DataBind();
            ViewState["DataTemp"] = ds;
            lbCount.Text = "记录数：" + AspNetPager1.RecordCount;
        }
        protected void AspNetPager1_PageChanged(object sender, EventArgs e)
        {
            if (bolFlag)
                GVDataBind();
            else
                GVDataBindAll();
        }
        protected void GVinfo_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            try
            {
                GVinfo.EditIndex = -1;
                GVinfo.DataSource = (DataSet)ViewState["DataTemp"];
                GVinfo.DataBind();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        protected void GVinfo_RowDataBound(object sender, GridViewRowEventArgs e)
        {
        }

        protected void GVinfo_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            try
            {
                string strID = ((HiddenField)GVinfo.Rows[e.RowIndex].FindControl("HF2")).Value;
                DbHelperSql.ExecuteSql(string.Format("DELETE FROM T_Area WHERE ID={0}", strID));
                GVinfo.DataSource = (DataSet)ViewState["DataTemp"];
                GVinfo.DataBind();
                MM.DBUtility.BLSqlData.InsertLogs(userModel.UserID, string.Format("删除了区域信息：ID={0}。", strID), "区域管理");
                MM.Common.Common.PageStartAlert(this.Page, "删除成功！");
                GVDataBindAll();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        protected void GVinfo_RowEditing(object sender, GridViewEditEventArgs e)
        {
            try
            {
                GVinfo.EditIndex = e.NewEditIndex;
                GVinfo.DataSource = (DataSet)ViewState["DataTemp"];
                GVinfo.DataBind();
                string strProvinceID = ((HiddenField)GVinfo.Rows[e.NewEditIndex].FindControl("hdfProvinceID")).Value.Trim();
                DropDownList ddlProvince = ((DropDownList)GVinfo.Rows[e.NewEditIndex].FindControl("ddlProvince"));
                BindDll(ref ddlProvince);
                ddlProvince.SelectedValue = strProvinceID;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        protected void GVinfo_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            try
            {
                string strCityName = ((TextBox)GVinfo.Rows[e.RowIndex].FindControl("txtCityName")).Text.Trim();
                if (string.IsNullOrEmpty(strCityName))
                {
                    MM.Common.Common.PageStartAlert(this.Page, "城市名不能为空！");
                    return;
                }

                string strProvinceID = ((DropDownList)GVinfo.Rows[e.RowIndex].FindControl("ddlProvince")).SelectedValue;
                string strID = ((HiddenField)GVinfo.Rows[e.RowIndex].FindControl("HF1")).Value;

                MM.DBUtility.DbHelperSql.ExecuteSql(string.Format("UPDATE T_Area SET CityName=N'{0}',ProvinceID='{1}' WHERE ID={2}", strCityName, strProvinceID, strID));
                MM.DBUtility.BLSqlData.InsertLogs(userModel.UserID, string.Format("更新了区域：ID={0}。", strID), "区域管理");
                MM.Common.Common.PageStartAlert(this.Page, "更新成功！");

                GVinfo.EditIndex = -1;
                GVDataBindAll();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        protected void GVinfo_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            GVinfo.PageIndex = e.NewPageIndex;
            GVinfo.DataSource = (DataSet)ViewState["DataTemp"];
            GVinfo.DataBind();
        }
        #endregion

        private void BindDll(ref DropDownList ddlProvince)
        {
            ddlProvince.DataSource = BLSqlData.AllProvince;
            ddlProvince.DataValueField = "ProvinceID";
            ddlProvince.DataTextField = "ProvinceName";
            ddlProvince.DataBind();
        }

    }
}
